var service = new EbeimService();
var status = "";
var $dsId = "";
$(function() {
	var dsType = $("#srch_type").val();
	var name = $("#srch_name").val();
	service.getDataSourcesByPage($offset, $pagesize, dsType, status, encodeURIComponent(encodeURIComponent(name)),
			callback);
	setInterval("getUploadProcessBar()", 2500);
});

function page(flag) {

	if (flag == "first") {
		$currentpage = 1;
	} else if (flag == "last") {
		$currentpage = ($totalpage==0?1:$totalpage);
	} else if (flag == "prev") {
		if ($currentpage - 1 <= 0) {
			return;
		}
		$currentpage--;
	} else if (flag == "next") {
		if ($currentpage + 1 > $totalpage) {
			return;
		}
		$currentpage++
	} else if (!isNaN(flag)) {
		if (flag > $totalpage || flag < 1) {
			alert("超出范围");
			return;
		}
		$currentpage = flag * 1;
	}
	$("#w-page").val($currentpage);
	// 由于调用了API的page对象，所以这里$offset 要等于$currentpage
	$offset = $currentpage;
	var dsType = $("#srch_type").val();
	var name = $("#srch_name").val();
	service.getDataSourcesByPage($offset, $pagesize, dsType, status, encodeURIComponent(encodeURIComponent(name)),
			callback);
}

function translateStatus(status, dsId) {
	if (status == 0) {
		status = "<div class='processbar' dsid='"
				+ dsId
				+ "' style='background:#ddd;width:100%;height:20px;position:relative;'>"
				+ "<div class='bar' style='height:20px;'></div>"
				+ "<div class='info' style='height:20px;color:gray;width:200px;position:absolute;top:0;left:0px;'>等待备份</div>"
				+ "</div>";
	} else if (status == 1) {
		status = "<div class='processbar' dsid='"
				+ dsId
				+ "' style='background:#ddd;width:100%;height:20px;border:solid 1px green;position:relative;'>"
				+ "<div class='bar' style='height:20px;'></div>"
				+ "<div class='info' style='width:200px;height:20px;color:#fff;position:absolute;top:0;left:0'></div>"
				+ "</div>";
	} else if (status == 2) {
		status = "<div class='processbar' dsid='"
				+ dsId
				+ "' style='background:#ddd;width:100%;height:20px;position:relative;'>"
				+ "<div class='bar' style='height:20px;'></div>"
				+ "<div class='info' style='height:20px;color:red;width:200px;position:absolute;top:0;left:0'>备份失败,请查看备份记录</div>"
				+ "</div>";
	} else if (status == 3) {
		status = "<div class='processbar' dsid='"
				+ dsId
				+ "' style='background:#ddd;width:100%;height:20px;position:relative;'>"
				+ "<div class='bar' style='height:20px;'></div>"
				+ "<div class='info' style='height:20px;color:green;width:200px;position:absolute;top:0;left:0'>备份成功，等待下次备份</div>"
				+ "</div>";
	} else if (status == 4) {
		status = "<div class='processbar' dsid='"
				+ dsId
				+ "' style='background:#ddd;width:100%;height:20px;position:relative;'>"
				+ "<div class='bar' style='height:20px;color:red'>禁用</div>"
				+ "</div>";
	}
	return status;
}

function getUploadProcessBar() {

	var ids = "";
	$(".processbar").each(function() {
		ids += $(this).attr("dsid") + ",";
	});
	if (ids.length > 0) {
		ids = ids.substring(0, ids.length - 1);
		service.getUploadProcessBar(ids, uploadPrcessBarCB);
		service.deleteUploadProcessBar(ids, delProcessbarCB);
	}
}

var uploadPrcessBarCB = function(data) {
	var json = eval("(" + data + ")");
	var list = json.beans;
	for (var i = 0; i < list.length; i++) {
		var bean = list[i];
		$(".processbar").each(
				function() {
					var dsid = $(this).attr("dsid");
					if (dsid == bean.dsId) {
						$(this).css("border", "solid 1px green");
						$(this).find(".bar").css("background", "green");
						$(this).find(".info").css("color", "#fff")
						if (bean.count >= bean.total) {
							$(this).find(".bar").css("width", 100 + "%");
							$(this).find(".info").html("100.00%");
							$(this).css("border", "0");
							$(this).find(".bar").css("width", 0);
							$(this).find(".info").css("color", "green")
							$(this).find(".info").html("备份成功，等待下次备份");
						} else {
							var p = (bean.count * 100 / bean.total).toFixed(2);
							$(this).find(".bar").css("width",p+ "%");
							if(p == 0){
								$(this).find(".info").html("正在加密中...");
							}else{
								$(this).find(".info").html(
										(bean.count * 100 / bean.total).toFixed(2)
												+ "%");
							}
						}

					}
				});
	}
}

var delProcessbarCB = function(data) {
	var json = eval("(" + data + ")");
}
function toPage(url){
	window.location.href = url;
}
var callback = function(data) {
	// alert(data);
	var json = eval("(" + data + ")");
	var list = json.list;
	var terminalId = json.terminalId;
	$total = json.page.totalRecord;
	$totalpage = Math.ceil($total / $pagesize);
	$("#c-page").html($currentpage);
	$("#t-page").html($totalpage == 0 ? 1 : $totalpage);
	var str = '';
	for (i = 0; i < list.length; i++) {
		var ds = list[i];
		var status = translateStatus(ds.status, ds.id);
		str += "<tr><td>" + ds.name + "</td>";
		str += "<td>" + ds.root + "</td>";
		str += "<td class='g-cgreen'>"
				+ (ds.dsType == 0 ? "文件夹" : (ds.dsType == 1 ? "数据库" : "数据保险箱"))
				+ "</td>";

		if (ds.terminalId == terminalId) {
			str += "<td><button class='btn btn-lg btn-info' onclick='javascript:toPage(\"datasource_detail.html?dsId="+ds.id+"\")'>详情</button>";
			str += "<button class='btn btn-lg btn-info' onclick='javascript:toPage(\"backuplogs.html?dsId=" + ds.id +"\")'>备份记录</button>";
			if (ds.status == 4) {
				str += "<button class='btn btn-lg btn-info' onclick='javascript:alert(\"请先启用该数据源\")'>手动备份</button>";
				str += "<button id='statusBtn"+ds.id+"' class='btn btn-lg btn-info' onclick='javascript:changeStatus(0,\"" + ds.id + "\","
						+ ds.dsSecurityRank + ")'>启用</button>";
			} else {
				str += "<button id='backupBtn"+ds.id+"' class='btn btn-lg btn-info' onclick='javascript:handBackup(\"" + ds.id + "\","
				+ ds.dsSecurityRank + ")'>手动备份</button>";
				str += "<button id='statusBtn"+ds.id+"' class='btn btn-lg btn-info' onclick='javascript:changeStatus(4,\"" + ds.id + "\","
						+ ds.dsSecurityRank + ")'>停用</button>";
			}
			str += "</td>";
			str += "<td>" + status + "</td>";
		} else {
			str += "<td>来自设备["
					+ (ds.bindDeviceName == undefined ? ds.terminalId
							: ds.bindDeviceName) + "]的数据源";
			str += "</td>";
			str += "<td></td>";
		}

		str += "</tr>";
	}
	if (list.length == 0) {
		str = "<tr><td style='text-align:center' colspan='5'>暂无数据</td></tr>";
	}
	$('#dsBody').html(str);
	$("#dsBody").find("tr:odd").find("td").css("background", "#fafafa")

}

function handBackup(dsId, dsSecurityRank, dynamicCode) {
	$("#h_whichGetModel").val("handBackup");
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#backupBtn"+dsId).attr("disabled","disabled");
	$dsId = dsId;
	service.backup(dsId, dsSecurityRank, dynamicCode, handBackupCB);
}

function setDynamicCode() {
	var dynamicCode = $("#dynamicCode").val();
	if (dynamicCode == "") {
		alert("动态验证码不能为空!");
		return;
	}
	var dsId = $("#h_dsId").val();
	var dsSecurityRank = $("#h_dsSecurityRank").val();
	var whichGetModel = $("#h_whichGetModel").val();
	if (whichGetModel == "handBackup") {
		handBackup(dsId, dsSecurityRank, dynamicCode)
	} else if (whichGetModel == "changeStatus") {
		var status = $("#h_status").val();
		changeStatus(status, dsId, dsSecurityRank, dynamicCode)
	}
}

var handBackupCB = function(data) {
	$("#backupBtn"+$dsId).removeAttr("disabled");
	var json = eval("(" + data + ")");
	if (json.code == "200" || json.code == 200) {
		alert("成功加入备份队列!");
		$('#myModal').modal("hide");
		$("#dynamicCode").val("");
	} else {
		dsSecurityRankCheck(json.code);
	}

}

function changeStatus(status, dsId, dsSecurityRank, dynamicCode) {
	$("#h_dsId").val(dsId);
	$("#h_dsSecurityRank").val(dsSecurityRank);
	$("#h_status").val(status);
	$("#h_whichGetModel").val("changeStatus");
	var ds = {
		id : dsId,
		status : status,
		dsSecurityRank : dsSecurityRank,
		dynamicCode : dynamicCode
	};
	$("#statusBtn"+dsId).attr("disabled","disabled");
	$dsId = dsId;
	var json = {};
	json["datasource"] = ds;
	service.addDataSource(json, changStatusCB);
}
var changStatusCB = function(data) {
	$("#statusBtn"+$dsId).removeAttr("disabled");
	var json = eval("(" + data + ")");
	if (json.code == "200") {
		$('#myModal').modal("hide");
		$("#dynamicCode").val("");
		var dsType = $("#srch_type").val();
		var name = $("#srch_name").val();
		service.getDataSourcesByPage($offset, $pagesize, dsType, status, encodeURIComponent(encodeURIComponent(name)),
				callback);
	} else {
		dsSecurityRankCheck(json.code);
	}
}
function filter(flag) {
	if(flag=="btn"){
		$currentpage = 1;
		$offset = 0;
		$("#w-page").val($currentpage);
	}
	var dsType = $("#srch_type").val();
	var name = $("#srch_name").val();
	service.getDataSourcesByPage($offset, $pagesize, dsType, status, encodeURIComponent(encodeURIComponent(name)),
			callback);
}
function resetInfo() {
	window.location.reload();
}